package com.traffic.between.service;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.Xml2JsonUtil;

public class WuYikaServiceImpl {
	private static Logger logger = Logger.getLogger(WuYikaServiceImpl.class);
	public static WuYikaServiceImpl service = new WuYikaServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.WUYIKA_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.WUYIKA_ORDERSTATUS_URL;
	private static String WUYIKA_KEY = BetweenProperties.WUYIKA_KEY;
	private static String WUYIKA_MERID = BetweenProperties.WUYIKA_MERID;

	
	public String order(String productId, String phoneNo, String cstmOrderNo,String ISP,String FlowType,String callbackURL) {
		
		String MerID = WUYIKA_MERID;
		String dateformat = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String waitSign = "Command=1&MerID="+MerID+"&OrderID="+cstmOrderNo+"&ChgMobile="+phoneNo+"&FlowAmount="+productId+"&ISP="+ISP+"&ReplyFormat=xml&InterfaceNumber=2.1.0.1&Datetime="+dateformat+"&Key="+WUYIKA_KEY;
		String sign = getMD5(waitSign);
	        
	    String result = "";
	    
	    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("Command", "1"));
        pairList.add(new BasicNameValuePair("MerID", MerID));
        pairList.add(new BasicNameValuePair("OrderID", cstmOrderNo));
        pairList.add(new BasicNameValuePair("ChgMobile", phoneNo));
        pairList.add(new BasicNameValuePair("FlowAmount", productId));
        pairList.add(new BasicNameValuePair("ISP", ISP));
        pairList.add(new BasicNameValuePair("ReplyFormat", "xml"));
        pairList.add(new BasicNameValuePair("InterfaceNumber", "2.1.0.1"));
        pairList.add(new BasicNameValuePair("Datetime",dateformat));
        pairList.add(new BasicNameValuePair("MerURL",callbackURL));
        pairList.add(new BasicNameValuePair("FlowType",FlowType));
        pairList.add(new BasicNameValuePair("Attach","flow"));
        pairList.add(new BasicNameValuePair("Sign",sign));
        
    	HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(30000).build();// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		logger.info("between- 五一卡订购请求时的参数: "+pairList);
        try {
        	
        	httpPost.setEntity(new UrlEncodedFormEntity(pairList, "gbk"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 五一卡流量订购请求时的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
				logger.info("between- 五一卡流量订购请求时的响应数据是: " + result);
				result = Xml2JsonUtil.xmlToJson(result);
			}
	       
		} catch (Exception e) {
			logger.info("bsm- 五一卡订购请求响应的异常信息:"+e);
			Map<String,String> map = new HashMap<String, String>();
			if (e.getMessage().contains("Read timed out")) {
				map.put("TranStat","0000");
				map.put("TranInfo",e.getMessage());
			}else {
				map.put("TranStat","9999");
				map.put("TranInfo",e.getMessage());
			}
			
			result = new Gson().toJson(map);
		}
        
        return result;
		
	}
	
	
	
	public String orderStatus(String cstmOrderNo,String mobile) {
		logger.info("bsm- 五一卡状态WuYikaServiceImpl.orderStatus() 查询请求cstmOrderNo = " + cstmOrderNo+",mobile="+mobile);
		String result = "";	
		String dateformat = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String waitSign = "Command=2&MerID="+WUYIKA_MERID+"&OrderID="+cstmOrderNo+"&ChgMobile="+mobile+"&ReplyFormat=xml&InterfaceNumber=2.0.0.1&Datetime="+dateformat+"&Key="+WUYIKA_KEY;
		String sign = getMD5(waitSign);
		
		List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
		pairList.add(new BasicNameValuePair("Command", "2"));
		pairList.add(new BasicNameValuePair("MerID", WUYIKA_MERID));
		pairList.add(new BasicNameValuePair("OrderID", cstmOrderNo));
		pairList.add(new BasicNameValuePair("ChgMobile", mobile));

		pairList.add(new BasicNameValuePair("ReplyFormat", "xml"));
		pairList.add(new BasicNameValuePair("InterfaceNumber", "2.0.0.1"));
		pairList.add(new BasicNameValuePair("Datetime", dateformat));

		pairList.add(new BasicNameValuePair("Attach", "flow"));
		pairList.add(new BasicNameValuePair("Sign", sign));

		HttpPost httpPost = new HttpPost(HOST_ORDERSTATUS_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "gbk"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 五一卡流量查询请求时的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
				logger.info("between- 五一卡流量查询请求时的响应数据是: " + result);
				result = Xml2JsonUtil.xmlToJson(result);
			}
	       
		} catch (Exception e) {
			logger.info("bsm- 五一卡查询请求响应的异常信息:"+e);
			Map<String, String> map = new HashMap<String, String>();
			map.put("TranStat", "1004");
			map.put("TranInfo", "订购查询异常，请稍后");
			result = new Gson().toJson(map);
			
		}
		return result;
	}
	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5 " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toUpperCase();// 字母大写
	}
}
